import {Component, OnInit, ViewChild} from '@angular/core';
import * as moment from 'moment';
import {ModalDirective} from 'ngx-bootstrap';
import {LoginService} from '../../lib/service/login.service';
import {Router} from '@angular/router';
import {HomeConfigService} from "../../lib/service/home/home-config.service";
import {AliyunOssOutputUrl} from '../../../config/api';
import {LocalStorageService} from '../../lib/service/local-storage.service';

export class LoginData {
    code: number;
    data: {
        user: {
            id: number,
            user_uuid: string,
            name: string,
            nick_name: string,
            email: string,
            mobile: string,
            remember_token: string,
            sex: string,
            avatar: string,
            isLock: number,
            lock_time: Date,
            openning_time: Date,
            created_at: Date,
            updated_at: Date,
            remark: string,
            time: string,
            a: string,
            p: string
        },
        token: {
            "access_token": string,
            "token_type": string,
            "expires_in": number,
            "expires_at": Date
        }
    };
    message: string;
    time: string;
}



@Component({
    selector: 'app-index-header',
    templateUrl: './index-header.component.html',
    styleUrls: ['./index-header.component.scss'],
    providers: [
        LoginService,
        HomeConfigService,
        LocalStorageService
    ]
})

export class IndexHeaderComponent implements OnInit {

    account = '';
    password = '';
    homeConfig;
    hadLoginName = '';
    head_nav_show = false;
    aliyunOssOutputUrl = AliyunOssOutputUrl;

    constructor(private loginService: LoginService,
                private router: Router,
                private homeConfigService: HomeConfigService,
                private localStorageService: LocalStorageService) {
    }

    ngOnInit() {
        this.getHomeConfig();
        const auth = this.localStorageService.getUserInfo();
        if (!!auth) {
          this.checkLoginInfo(auth);
        }
    }

    // 检查登录信息 查看是否过期
    checkLoginInfo(auth) {
      // 创建时间
      const time = parseInt(auth.time, 10);
      // 过期时间
      const expireTime = time + 3600;
      // 当前时间
      const nowTime = parseInt(moment().format('X'), 10);
      if (expireTime < nowTime) {
        alert("登录信息过期，请重新登录");
        this.localStorageService.clearAll();
        this.hadLoginName = '';
        this.router.navigate(['/home/index']);
        return false;
      } else {
        this.hadLoginName = auth.nick_name;
      }
    }

    getHomeConfig() {
        this.homeConfigService.getHomeConfig().subscribe(
            res => {
                if (res.code === 2000) {
                    this.homeConfig = res.data;
                } else {
                    alert(res.code + ',' + res.message);
                }
            }
        );
    }


}
